package com.bs.demo.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author bingshao
 * @date 2023/5/15
 **/
@RestController
@RequestMapping("/scheduledExecutorService")
public class ScheduledExecutorServiceTest {

    private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
    int i = 1;
    int j = 1;

    @PostMapping("/setTask")
    public void setTask() {
        scheduledExecutorService.schedule(() -> System.out.println("runnable任务启动"), 5, TimeUnit.SECONDS);

        scheduledExecutorService.schedule(() -> "callable任务启动", 5, TimeUnit.SECONDS);

        // 只按照间隔时间，不管上一个任务是否完成
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            System.out.println("scheduleAtFixedRate: " + System.currentTimeMillis());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第" + i + "次的scheduleAtFixedRate方法");
            i++;
        }, 5, 2, TimeUnit.SECONDS);

        // 上一个任务完成后等待间隔时间再执行下一次
        scheduledExecutorService.scheduleWithFixedDelay(() -> {
            System.out.println("scheduleAtFixedRate: " + System.currentTimeMillis());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第" + j + "次的scheduleWithFixedDelay方法");
            j++;
        }, 5, 2, TimeUnit.SECONDS);
    }
}
